package com.myblog.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.myblog.common.lang.Result;
import com.myblog.entity.Blog;
import com.myblog.service.IBlogService;
import com.myblog.util.ShiroUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 沉梦听雨
 * @since 2023-03-25
 */
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    IBlogService blogService;

    /**
     * 分页查询博客
     * @param currentPage
     * @return
     */
    @GetMapping("/list")
    public Result blogs(@RequestParam(defaultValue = "1") Integer currentPage) {
        if(currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        Page<Blog> page = new Page<>(currentPage, 5);
        IPage<Blog> pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));

        return Result.succ(pageData);
    }

    /**
     * 查某个博客
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已删除！");
        return Result.succ(blog);
    }

    /**
     * 修改博客数据
     * @param blog
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/edit")
    public Result edit(@Validated @RequestBody Blog blog) {
        System.out.println(blog.toString());

        Blog temp = null;
        // 判断博客是否为null
        if(blog.getId() != null) {
            // 1、不为null
            temp = blogService.getById(blog.getId());
            // 判断temp对象所属的用户是否为当前登录用户
            Assert.isTrue(temp.getUserId().equals(ShiroUtil.getProfile().getId()), "没有权限编辑");
        } else {
            // 2、为null，表示这是一个新的博客对象，需要设置一些初始值
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(1);
        }
        // 将blog复制给temp
        BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");

        blogService.saveOrUpdate(temp);
        return Result.succ( null);
    }

    /**
     * 模糊查询
     * @param currentPage
     * @param pageSize
     * @param blog
     * @return
     */
    @GetMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable int currentPage, @PathVariable int pageSize, Blog blog) {

        IPage<Blog> page = blogService.getPage(currentPage, pageSize, blog);
        //如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()) {
            page = blogService.getPage((int) page.getPages(), pageSize, blog);//一次性删除过多可能有bug
        }
        return Result.succ( page);
    }
}
